package com.ykdl.member.kid.regandlogin;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import net.wxxr.http.util.Constants;
import oauth.signpost.http.HttpParameters;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.umeng.analytics.MobclickAgent;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.beans.LaunchBean;
import com.ykdl.member.kid.beans.RegisterPhonebean;
import com.ykdl.member.kid.beans.ResetPasswordBean;
import com.ykdl.member.kid.beans.Web_socket_worker;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.gears.HomeActivity;
import com.ykdl.member.kid.prefs.MyPrefs;
import com.ykdl.member.kid.regandlogin.ForgetPwOneActivity.MyCount;
import com.ykdl.member.kid.regandlogin.ForgetPwOneActivity.getverifyCodeTag;
import com.ykdl.member.kid.util.AccessTokenKeeper;
import com.ykdl.member.kid.util.ResoureUtil;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class YZLoginActivity extends BaseScreen implements OnClickListener {

	private EditText user_number, veri_code;
	private Button sen_bt;
	private MyCount mc;
	private String phoneNumber = "";
	private Button login_bt;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTopTitle("登录", 0, 0, null, 0, 0, null, R.drawable.title_bg, false);
		setContent(R.layout.activity_yzlogin);
		ResoureUtil.activityList.add(this);
		initUI();
	}

	private void initUI() {
		// TODO Auto-generated method stub
		user_number = (EditText) findViewById(R.id.user_number);
		user_number.addTextChangedListener(mTextWatcher);
		user_number.setInputType(EditorInfo.TYPE_CLASS_PHONE);
		
		sen_bt = (Button) findViewById(R.id.sen_bt);
		sen_bt.setEnabled(false);
		sen_bt.setOnClickListener(this);

		login_bt = (Button) findViewById(R.id.login_bt);
		login_bt.setEnabled(false);
		login_bt.setOnClickListener(this);

		veri_code = (EditText) findViewById(R.id.veri_code);
		veri_code.addTextChangedListener(watcher);
		veri_code.setInputType(EditorInfo.TYPE_CLASS_PHONE);
	}

	TextWatcher mTextWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			if (checkPhone()) {// 手机号输入完毕
				sen_bt.setBackground(getResources().getDrawable(
						R.drawable.red_bg));
				sen_bt.setEnabled(true);
				phoneNumber = user_number.getText().toString().trim();
			} else {
				sen_bt.setEnabled(false);
				sen_bt.setBackground(getResources().getDrawable(
						R.drawable.gray_bg));
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
		}
	};

	TextWatcher watcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			if (s.length()==6 && checkPhone()) {
				login_bt.setBackground(getResources().getDrawable(
						R.drawable.log_red_bg));
				login_bt.setEnabled(true);
			} else {
				login_bt.setBackground(getResources().getDrawable(
						R.drawable.log_gray_bg));
				login_bt.setEnabled(false);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
		}
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.sen_bt:
			if (isConnect(this)) {
				if (phoneNumber.length() == 11) {
					goRestPw(phoneNumber);// 手机号
				} else {
					Toast.makeText(mContext, "请输入正确的手机号", 1).show();
					return;
				}

			} else {
				Toast.makeText(mContext, "请连接网络", 1).show();
				return;
			}
			break;
		case R.id.login_bt:
			goNativeLogin();

			break;

		default:
			break;
		}

	}

	public void goRestPw(String phoneString) {
		showProgress("正在发送请稍等...");
		String pageurl = KidConfig.REGISTER_BYPHONE;
		HttpParameters parameterss = new HttpParameters();
		parameterss.put("app_key", "hsh");
		parameterss.put("phone", phoneString);
		parameterss.put("client_id", Constants.CLIENT_ID);
		parameterss.put("client_secret", Constants.CLIENT_SECRET);
		parameterss.put("type", "common");
		HttpBaseRequest request = Wxxr.getInstance().postBaseRequest(pageurl,
				parameterss, null);
		TaskManager.startHttpRequest(request, new getverifyCodeTag(),
				ResetPasswordBean.class);
	}

	class getverifyCodeTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			if (t instanceof ResetPasswordBean) {
				finishProgress();
				ResetPasswordBean bean = (ResetPasswordBean) t;
				if (bean.getError() != null) {
					Toast.makeText(mContext,  bean.getDesc(), 1).show();
				} else {
					if (bean.getStatus() == 0) {
						Toast.makeText(mContext, "成功", 1).show();
						Log.e("alan", "-------t:" + t.toString());
						sen_bt.setBackground(getResources().getDrawable(
								R.drawable.gray_bg));
						mc = new MyCount(60000, 1000);
						mc.start();
						// gonext() ;
					} else {
						Toast.makeText(mContext,  bean.getDesc(), 1)
								.show();
					}

				}
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "参数有误失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
	}

	class MyCount extends CountDownTimer {

		public MyCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onTick(long millisUntilFinished) {
			// TODO Auto-generated method stub
			sen_bt.setEnabled(false);
			sen_bt.setText(millisUntilFinished / 1000 + "重新获取");
		}

		@Override
		public void onFinish() {
			// TODO Auto-generated method stub
			sen_bt.setEnabled(true);
			sen_bt.setBackground(getResources().getDrawable(R.drawable.red_bg));
			sen_bt.setText("获取验证码");
		}
	}

	// 登陆

	public void goNativeLogin() {
		if (!checkPhone()) {
			return;
		}
		if (veri_code.getText().toString().trim().length() < 1) {
			Toast.makeText(mContext, "请输入验证码", 1).show();
			return;
		}
		showProgress("正在登录请稍等...");
		String pageurl = KidConfig.GET_ACCESS_TOKEN;
		HttpParameters bodyParams = new HttpParameters();
		bodyParams.put("client_id", Constants.CLIENT_ID);
		bodyParams.put("client_secret", Constants.CLIENT_SECRET);
		bodyParams.put("phone", user_number.getText().toString()); // 手机号
		bodyParams.put("confirm_code", veri_code.getText().toString()); // 验证码
		bodyParams.put("grant_type", "phone");
		HttpBaseRequest request = Wxxr.getInstance().postBaseRequest(pageurl,
				bodyParams, null);
		TaskManager.startHttpRequest(request, new goRegisterTag(),
				RegisterPhonebean.class);
	}

	class goRegisterTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			Log.e("alan", "------------goRegisterTag:" + t.toString());
			if (t instanceof RegisterPhonebean) {
				finishProgress();
				RegisterPhonebean bean = (RegisterPhonebean) t;
				if (bean.getDesc() != null) {
					if (bean.getError().equals("20501")) {//没有注册的情况
						Intent intent=new Intent(mContext, PhoneNumberRegisterTwoActivity.class);
						//将手机号和验证码传递到 PhoneNumberRegisterTwoActivity
						intent.putExtra("phone_number", user_number.getText().toString()); 
						intent.putExtra("verifyCode",veri_code.getText().toString());
						startActivity(intent);
						finish();
					}else{
						Toast.makeText(mContext, bean.getDesc(), 1).show();
					}
				
				} else {
					AccessTokenKeeper.keepAccessToken(YZLoginActivity.this,
							bean);
					getWeb_socket();
					Toast.makeText(mContext, "登录成功", 1).show();
					MobclickAgent.onEvent(YZLoginActivity.this,
							"register_users");
					istutorial();
					
				}
				Log.e("alan",
						"------------Access_token:" + bean.getAccess_token());
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "失败", 1).show();
			return true;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
	}

	// 验证是否是手机号
	public boolean checkPhone() {
		if (user_number.getText().toString().length() == 11) {
			if (user_number.getText().toString().matches("[0-9]{1,}")) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	// websocket
	public void getWeb_socket() {
		String pageurl = KidConfig.GET_WEB_SOCKET;
		HttpParameters bodyParams = new HttpParameters();
		HttpBaseRequest request = Wxxr.getInstance().getBaseRequest(pageurl);
		TaskManager.startHttpRequest(request, new getWeb_socketTag(),
				Web_socket_worker.class);
	}

	class getWeb_socketTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			if (t instanceof Web_socket_worker) {
				Web_socket_worker bean = (Web_socket_worker) t;
				if (null == bean.getError()) {
					MyPrefs.setweb_socket(mContext, "http://"
							+ bean.getWeb_socket_worker().getHost() + ":"
							+ bean.getWeb_socket_worker().getPort());
				} else {
					Toast.makeText(mContext, "失败," + bean.getDesc(), 1).show();
				}
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub

		}
	}

	// ----------------------登陆后跳到哪个页面----------
	public void istutorial() {
		showProgress("正在登录请稍等...");
		String pageurl = KidConfig.APP_INIT;
		HttpBaseRequest request = Wxxr.getInstance().getBaseRequest(pageurl);
		TaskManager.startHttpRequest(request, new tutorialTag(),
				LaunchBean.class);
	}

	class tutorialTag implements ITag {
		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			LaunchBean launchBean = (LaunchBean) t;
			if (launchBean.getError() == null) {
				if (launchBean.getTutorial() == 0) {
					go(StateSelectActivity.class);
					YZLoginActivity.this.finish();
				} else {
					go(HomeActivity.class);
					YZLoginActivity.this.finish();
				}
			} else {
				go(HomeActivity.class);
				YZLoginActivity.this.finish();
			}
			if (launchBean.getJpush_tags() != null) {
				Set<String> set = new HashSet<String>(Arrays.asList(launchBean
						.getJpush_tags()));
				JPushInterface.setAliasAndTags(
						YZLoginActivity.this.getApplicationContext(),
						launchBean.getAlias(), set);
			} else {
				JPushInterface.setAliasAndTags(
						YZLoginActivity.this.getApplicationContext(),
						launchBean.getAlias(), null);
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
	}

}
